<template>
	<div class="update-photo">
		<img :src="img" class="img" ref="img">
		<div class="toolbar">
			<div class="cancel" @click="$emit('close')">取消</div>
			<div class="confirm" @click="onConfirm">完成</div>
		</div>
	</div>
</template>


<script>
	import Cropper from 'cropperjs'
	import 'cropperjs/dist/cropper.css'
	import {
		updateUserPhoto
	} from '@/api/user.js'

	export default {
		props: {
			img: {
				type: [String, Object],
				required: true
			}
		},

		data() {
			return {
				cropper: null
			}
		},

		mounted() {
			const image = this.$refs.img
			this.cropper = new Cropper(image, {
				viewMode: 1,
				dragMode: 'move',
				aspectRatio: 1,
				autoCropArea: 1,
				cropBoxMovable: false,
				cropBoxResizable: false,
				background: false
			})
		},

		methods: {
			onConfirm() {
				this.cropper.getCroppedCanvas().toBlob(async blob => {
					this.$toast.loading({
						message: '更新中',
						forbidClick: true,
						duration: 0
					})

					const formData = new FormData()
					formData.append('photo', blob)
					try {
						const {
							data: res
						} = await updateUserPhoto(formData)
						this.$store.commit('setUserPhoto', res.data.photo)
						this.$toast('更新头像成功')
					} catch (e) {
						this.$toast('更新头像失败')
					}
					this.$emit('close')
				})
			}
		},

	}
</script>

<style lang="less" scoped>
	.update-photo {
		background-color: #000;
		height: 100%;

		.img {
			max-width: 100%;
		}

		.toolbar {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			display: flex;
			justify-content: space-between;

			.cancel,
			.confirm {
				width: 90px;
				height: 90px;
				font-size: 30px;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #fff;
			}
		}
	}
</style>
